package com.huilian.netty.repository;

import com.huilian.netty.handler.CIMNioSocketAcceptor;
import com.huilian.netty.model.CIMSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 正式场景下，使用redis或者数据库来存储session信息
 */
@Slf4j
@Repository
public class SessionRepository {
    private ConcurrentHashMap<String, List<CIMSession>> map = new ConcurrentHashMap<>();
    @Value("${server.host}")
    private String host;
    @Resource
    private CIMNioSocketAcceptor nioSocketAcceptor;

    public void save(CIMSession session) {
        List<CIMSession> cimSessionList = map.get(session.getUsername());
        if (StringUtils.isEmpty(cimSessionList)) {
            cimSessionList = new ArrayList<>();
        }
        cimSessionList.add(session);
        map.put(session.getUsername(), cimSessionList);
    }

    public List<CIMSession> get(String username) {
        List<CIMSession> cimSessionList = map.get(username);
//        if(!StringUtils.isEmpty(map)) {
//            logger.info("全部的链接数: {}", map.size());
//        }
        if (!StringUtils.isEmpty(cimSessionList)) {
            cimSessionList.forEach(session -> {
                if (session != null) {
                    log.info("session.getNid():{}",session.getNid());
                    session.setSession(nioSocketAcceptor.getManagedSession(session.getNid()));
                }
            });
        }
        return cimSessionList;
    }

    public void remove(String username,String nId) {
        List<CIMSession> cimSessionList = this.get(username);
        if (cimSessionList != null && cimSessionList.size() > 0) {
            Iterator<CIMSession> it = cimSessionList.iterator();
            while (it.hasNext()) {
                CIMSession cimSession = it.next();
                /** 如果是账号已经在另一台终端登录。则让另一个终端下线*/
                if (nId.equals(cimSession.getNid())) {
                    it.remove();
                }
            }
            if(cimSessionList != null && cimSessionList.size() > 0) {
                map.put(username, cimSessionList);
            }else{
                map.remove(username);
            }
        }
    }
}
